package ext.acae2.dms.web.input;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

import org.apache.log4j.Logger;

import wt.content.ApplicationData;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.log4j.LogR;
import wt.util.WTException;
import wt.util.WTMessage;
import ext.acae2.dms.load.DocumentFactory;
import ext.acae2.dms.resource.DataExchangeResource;

public class DocumentProcessor {

    private static final Logger LOGGER = LogR.getLogger(DocumentProcessor.class.getName());
    private static final String RESOURCE = DataExchangeResource.class.getName();
    
    public Map<String, String> create(File file, String supplier) throws WTException, FileNotFoundException, PropertyVetoException, IOException {
        LOGGER.debug("> Start create");
        LOGGER.debug("supplier: " + supplier);
        Map<String, String> map = new HashMap<String, String>();
        
        String folder = "/Default/" + WTMessage.getLocalizedMessage(RESOURCE, "FOLDER_NAME_" + supplier) 
                + "/" + WTMessage.getLocalizedMessage(RESOURCE, DataExchangeResource.ROOT_FOLDER_NAME) 
                + "/" + WTMessage.getLocalizedMessage(RESOURCE, DataExchangeResource.IMPORT_FOLDER_NAME);
        
        LOGGER.debug("folder: " + folder);
        
        String libName = WTMessage.getLocalizedMessage(RESOURCE, DataExchangeResource.LIB_NAME);
        
        WTDocument doc = DocumentFactory.getInstance().createCommonDocumentToFolder(
                WebConstants.DATA_PACK_TYPE, file.getName(), libName, folder);
        LOGGER.debug("doc: " + doc.getNumber());
        
        ApplicationData appData = ApplicationData.newApplicationData(doc);
        appData.setFileName(file.getName());
        appData.setRole(ContentRoleType.PRIMARY);
        FileInputStream fis = new FileInputStream(file);
        ContentServerHelper.service.updateContent(doc, appData, fis);
        ContentServerHelper.service.updateHolderFormat(doc);
        
        LOGGER.debug("> End create");
	map.put("number", doc.getNumber());
	map.put("path", folder);
	return map;
    }
}
